package com.lucky.carcodepro.config;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSON;
import com.lucky.carcodepro.common.CurrentContextHolder;
import com.lucky.carcodepro.domain.bo.CurrentContextBo;
import com.lucky.carcodepro.domain.model.UserInfo;
import com.lucky.carcodepro.utils.HttpUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Order(1)
@Configuration
public class RequestHeaderInterceptorConfig implements WebMvcConfigurer {

    /**
     * 注册拦截器
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptor() {
            // 匿名内部类实现
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                // 把请求头的关键参数 Set 入 Bo，在上下文中使用
                CurrentContextBo bo = new CurrentContextBo()
                        .setUri(request.getRequestURI())
                        .setAllHeaders(HttpUtils.getHeaders(request));
                if (StpUtil.isLogin()) {
                    bo.setUser(
                            JSON.parseObject(
                                    StpUtil.getExtra(CurrentContextBo.Fields.user).toString(), UserInfo.class
                            )
                    );
                }
                CurrentContextHolder.set(bo);
                return true;
            }

            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
                // 清理上下文，避免内存泄露
                CurrentContextHolder.clear();
            }
        }).addPathPatterns("/**");
    }
}
